<template>
  <div ref="countToRef" :class="className" :style="styles">{{ formattedValue }}</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue';
import { CountUp } from 'countup.js';

interface Props {
  start: number;
  end: number;
  duration: number;
  className?: string;
  style?: Record<string, string>;
  options?: Record<string, any>;
}

const props = withDefaults(defineProps<Props>(), {
  start: 0,
  duration: 2,
  className: '',
  style: () => ({}),
  options: () => ({})
});

const countToRef = ref<HTMLElement | null>(null);
const formattedValue = ref<number>(props.start);

let countUpInstance: CountUp | null = null;

const startCountUp = () => {
  if (countToRef.value) {
    countUpInstance = new CountUp(countToRef.value, props.end, {
      duration: props.duration,
      ...props.options
    });

    if (!countUpInstance.error) {
      countUpInstance.start();
    } else {
      console.error(countUpInstance.error);
    }
  }
};

onMounted(() => {
  startCountUp();
});

onBeforeUnmount(() => {
  if (countUpInstance) {
    countUpInstance.reset();
  }
});

watch(() => props.end, (newEnd) => {
  if (countUpInstance) {
    countUpInstance.update(newEnd);
  }
});

const styles = computed(() => ({
  ...props.style
}));
</script>

<style scoped>
/* 你可以在这里添加自定义样式 */
</style>